﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SAAS.ServiceInterface;
using System.IO;

namespace SAAS.FilesManager
{
    public partial class MainForm : Form
    {
        private long totalLength = 0;
        private const int maxSize = SAAS.ServiceInterface.Constants.MaxLength;

        public MainForm()
        {
            InitializeComponent();
        }

        private void SelectFileButton_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (!String.IsNullOrEmpty(openFileDialog1.FileName))
                {
                    SelectFileTextBox.Text = openFileDialog1.FileName;
                    if(File.Exists(openFileDialog1.FileName))
                    {
                        using(FileStream fs =new FileStream(openFileDialog1.FileName,FileMode.Open,FileAccess.Read))
                        {
                            totalLength = (fs.Length / 1024);
                            UploadedLabel.Text = "0 k/" + totalLength + " k";  
                            fs.Close();
                        }
                    }
                }
            }
        }

        private void UploadButton_Click(object sender, EventArgs e)
        {
            progressBar1.Value = 0;
            backgroundWorker1.RunWorkerAsync("upload");
        }

        private void CLoseButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            var fileManager = ServiceBroker.FindService<IFileManager>();
            #region upload 
            if ((string)e.Argument == "upload")
            {
                string localPath = SelectFileTextBox.Text;
                string fileName = localPath.Substring(localPath.LastIndexOf('\\') + 1);
                FileStream stream = System.IO.File.OpenRead(localPath);
                FileData file = fileManager.GetFiles(fileName);
                if (file == null)
                {
                    file = new FileData();
                    file.Offset = 0;
                }
                file.Name = fileName;
                file.Length = stream.Length;
                if (file.Length == file.Offset)
                {
                    MessageBox.Show("The file has existed in the Server", "Notice", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                else
                {
                    while (file.Length != file.Offset)
                    {
                        file.Data = new byte[file.Length - file.Offset <= maxSize ? file.Length - file.Offset : maxSize];
                        stream.Position = file.Offset;
                        stream.Read(file.Data, 0, file.Data.Length);
                        file = fileManager.UplodaFile(file);

                        e.Result = file.Offset;
                        (sender as BackgroundWorker).ReportProgress((int)(((double)file.Offset / (double)((long)file.Length)) * 100), file.Offset);

                        if (this.backgroundWorker1.CancellationPending)
                            return;
                    }

                }
                stream.Close();
            }
            #endregion

            #region download
            else
            {
                string fileFullPath = SelectFileTextBox.Text;
                string fileName = fileFullPath.Substring(fileFullPath.LastIndexOf('\\') + 1);
                FileData file = new FileData()
                {
                    Name = fileFullPath,
                    Data = null,
                    Length = long.MaxValue,
                    Offset = 0
                };
                string saveFilePath = @"E:\VS Sample\SAASInvest\SAAS.FilesManager\Download";
                string saveFileFullPath = Path.Combine(saveFilePath, fileName);
                using (FileStream fs = new FileStream(saveFileFullPath, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    BinaryWriter binaryWriter = new BinaryWriter(fs);
                    while (file.Offset < file.Length)
                    {
                        binaryWriter.BaseStream.Position = file.Offset;
                        file = fileManager.DownlownFile(file);
                        binaryWriter.Write(file.Data);
                        file.Offset = fs.Length;
                        e.Result = file.Offset;
                        (sender as BackgroundWorker).ReportProgress((int)(((double)file.Offset / (double)((long)file.Length)) * 100), file.Offset);
                        if (this.backgroundWorker1.CancellationPending)
                            return;
                    }
                    binaryWriter.Close();
                    fs.Close();
                }
            }
            #endregion
            ServiceBroker.DisposeService<IFileManager>(fileManager);
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
            UploadedLabel.Text = (((long)e.UserState) / 1024).ToString() + " k/" + totalLength + " k";            
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (!e.Cancelled)
            {
                if (e.Error != null)
                {
                    MessageBox.Show(e.Error.Message);
                }
                else
                {
                    MessageBox.Show("Upload Successful!");
                }
            }
        }

        private void DownloadButton_Click(object sender, EventArgs e)
        {
            progressBar1.Value = 0;
            backgroundWorker1.RunWorkerAsync("download");
        }
    }
}
